import 'package:bi_project/http/core/dio_adapter.dart';
import 'package:bi_project/http/core/mock_adapter.dart';

import 'hi_error.dart';

import '../request/base_request.dart';
import 'hi_net_adapter.dart';

class HiNet {
  static HiNet? _instance;

  HiNet._();

  static HiNet getInstance() {
    // ignore: prefer_conditional_assignment
    if (_instance == null) {
      _instance = HiNet._();
    }
    return _instance!;
  }

  Future fire(BaseRequest request) async {
    NiNetResponse? response;
    var error;
    try {
      response = await send(request);
    } on HiNetError catch (e) {
      error = e.message;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      error = e;
      printLog(error);
    }

    if (response == null) {
      printLog(error);
    }

    var result = response?.data;
    var status = response?.statusCode;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw HiNetError(status!, result.toString(), data: result);
    }
  }

  Future<dynamic> send<T>(BaseRequest request) async {
    printLog("url:${request.url()}");

    HiNetAdapter adapter = DioAdapter();

    return adapter.send(request);
  }

  printLog(String str) {
    print(str);
  }
}
